package com.xsm.activitygroup;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.message.BasicNameValuePair;

import com.umeng.analytics.MobclickAgent;
import com.xsm.activitygroup.R;
import com.xsm.internet.PostMessage;
import com.xsm.view.LoadDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Register extends Activity{
	com.xsm.view.ClearEditText  user,password,ensurepass,email;
	String userString,passwordString,ensureString,emailString;
	RegisterHandler handler;
	String errortext;
	Context context;
	String resultString;
	LinearLayout rlayout,rsuccess;
	LoadDialog dialog;
	private Spinner school;
	String place="";
	String logtype="",sex="",name="",icon="";
	TextView idtext;
	String userid="";
protected void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.register);
	handler=new RegisterHandler();
	context =this;
	logtype=getIntent().getExtras().getString("type");
	sex=getIntent().getExtras().getString("sex");
	name=getIntent().getExtras().getString("name");
	icon=getIntent().getExtras().getString("icon");
	idtext=(TextView)findViewById(R.id.idtext);
	initView();
	
}


private void initView(){
	final String s2[]=new String[]{"广州中医药大学","广东药学院","华南理工大学","广东工业大学","广州大学","广州美术学院","华南师范大学","星海音乐学院","中山大学","广东外语外贸大学"};
	 ArrayAdapter<String> adapter2=new ArrayAdapter<String>(this, R.layout.myspinner,s2);	
	school=(Spinner)findViewById(R.id.school);
	user=(com.xsm.view.ClearEditText  )findViewById(R.id.euser);
	email=(com.xsm.view.ClearEditText  )findViewById(R.id.email);
	user.setText(getNativePhoneNumber());
	password=(com.xsm.view.ClearEditText  )findViewById(R.id.epassword);
	ensurepass=(com.xsm.view.ClearEditText  )findViewById(R.id.ensurepass);
	rlayout=(LinearLayout)findViewById(R.id.rlayout);
	rsuccess=(LinearLayout)findViewById(R.id.rsuccess);
	school.setAdapter(adapter2);
	school.setOnItemSelectedListener(new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			place=s2[arg2];
		}
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	 });
}



public String getNativePhoneNumber() {
	 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String NativePhoneNumber=null;
      NativePhoneNumber=telephonyManager.getLine1Number();
      if(NativePhoneNumber==null)
    	  NativePhoneNumber="";
      return NativePhoneNumber;
  }


public void Back(View view){
	finish();
}

public void Success(View view){
	Intent intent=new Intent();
	intent.putExtra("user", userid);
	intent.putExtra("password",passwordString);
	setResult(RESULT_OK, intent);
	finish();
}

public void RegisterButton(View view){
	final Message msg=handler.obtainMessage();
	        userString=user.getText().toString().trim();
			passwordString=password.getText().toString().trim();
			ensureString=ensurepass.getText().toString().trim();
			emailString=email.getText().toString().trim();	
			if(userString.equals("")|password.equals("")|ensureString.equals("")){
				errortext="请输入完整信息";
			}else {
			if(!passwordString.equals(ensureString)){
			 errortext="密码与确认密码不一致";
			}
			else if(!isMobileNum(userString)){
				errortext="请输入正确号码";
			}else if(!isEmail(emailString)){
				errortext="请输入正确的邮箱";
			}
			else{
			if(password.length()<6){
				 errortext="密码长度过短";	
			}else{
				final String	Imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
				dialog=	new LoadDialog(context, "正在注册,请稍候...");
				dialog.showDialog();
				errortext="";		
				//注册
				new Thread(new Runnable() {
					public void run() {
						List params=new ArrayList();
						params.add(new BasicNameValuePair("ASK","Register"));
						params.add(new BasicNameValuePair("user",userString));
						params.add(new BasicNameValuePair("password",passwordString));
						params.add(new BasicNameValuePair("school",place));
						params.add(new BasicNameValuePair("phone",Imei));
						params.add(new BasicNameValuePair("email",emailString));
						params.add(new BasicNameValuePair("other",logtype));
						params.add(new BasicNameValuePair("sex",sex));
						params.add(new BasicNameValuePair("name",name));
						params.add(new BasicNameValuePair("icon",icon));
						PostMessage postMessage=new PostMessage(params);
						resultString=postMessage.getResult();	
						msg.what=1;
						handler.sendMessage(msg);
					}
				}).start();

				
			}	
				}
			}
			
		if(!errortext.equals("")){		
			msg.what=2;
			handler.sendMessage(msg);
		}

}

/**
 * 检测邮箱地址是否合法
 * @param email
 * @return true合法 false不合法
 */
public boolean isEmail(String email){
      if (null==email || "".equals(email)) return false;  
//    Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
      Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
      Matcher m = p.matcher(email);
      return m.matches();
     }

public static boolean isMobileNum(String mobiles) {
    Pattern p = Pattern .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
    Matcher m = p.matcher(mobiles);
    return m.matches();

}

class RegisterHandler  extends Handler{
	public void handleMessage(Message msg) {
		if(msg.what==1){
if(resultString.equals("1")){
Toast.makeText(context,"已注册的email",Toast.LENGTH_LONG).show();			
}
else if(resultString.equals("2")){
Toast.makeText(context,"已注册的手机号码",Toast.LENGTH_LONG).show();		
}else if(resultString.equals("3")){
	Toast.makeText(context,"本手机已被注册",Toast.LENGTH_LONG).show();		
}else if(resultString.equals("-1")){
	Toast.makeText(context,"连接服务器失败",Toast.LENGTH_LONG).show();			
}else{
	idtext.setText("恭喜用户"+resultString+"注册成功");
	rlayout.setVisibility(View.GONE);
	rsuccess.setVisibility(View.VISIBLE);
	userid=resultString;
}
dialog.dissmissDialog();
}else{
Toast.makeText(context,errortext,Toast.LENGTH_LONG).show();		
}
	}
}
@Override
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
@Override
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}
}
